package com.zhuxin.timer;

import com.CommWxApplication;
import com.dbHelper.DbTemplate;
import com.google.gson.Gson;
import com.soecode.wxtools.api.WxConsts;
import com.soecode.wxtools.api.WxService;
import com.soecode.wxtools.bean.*;
import com.soecode.wxtools.bean.result.SenderResult;
import com.soecode.wxtools.bean.result.TemplateSenderResult;
import com.soecode.wxtools.exception.WxErrorException;
import com.zhuxin.common.UtilTools;
import com.zhuxin.medical.model.po.CoPlanCanelinfo;
import com.zhuxin.medical.model.po.CoWxTemplateInfo;
import com.zhuxin.medical.model.po.CommAppLog;
import com.zhuxin.medical.model.po.CommWxUser;
import com.zhuxin.medical.mvc.controller.WxCtr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Transactional
public class TimerJobs {

    private static final Logger log = LoggerFactory.getLogger(TimerJobs.class);

    @Autowired
    private DbTemplate oracleDao;
    @Autowired
    private DbTemplate mysqlDao;
    @Value("${wx.templateid}")
    private String template_id;
    @Value("${wx.domainName.test}")
    private String domainName;//域名

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private WxService wxService;

    public void disLog() throws WxErrorException {
        this.oracleDao.queryForObject("select 1 from dual",Integer.class);
        //5分钟未回复理由
        String sql="select * from commAppLog WHERE NOW()>DATE_ADD(`appletime`,interval 5 minute) AND STATUS=1";
        List<CommAppLog> logs=this.mysqlDao.querySub(sql,CommAppLog.class);
        logs.forEach(l->{
            l.setStatus(999L);
            this.mysqlDao.updateSub(l,"status",true);
            this.mysqlDao.update("update commWxUser set status=0 where openid=?",l.getOperid());
            String confirmUrl = domainName+"/wxPage/WxCancelPlanInit?infoId="+l.getRecid();
            StringBuffer sb=new StringBuffer("因你未回复申请理由，自动作废本次申请.");
            sb.append("<a href=").append("'").append(confirmUrl).append("'>详情")
                    .append("</a>");
            UtilTools.sendKfMsg(l.getOperid(),sb.toString());
        });

        //24小时超时
        sql="select * from commAppLog WHERE NOW()>DATE_ADD(`appletime`,INTERVAL 24 HOUR) AND STATUS=2";
        logs=this.mysqlDao.querySub(sql,CommAppLog.class);
        logs.forEach(l->{
            l.setStatus(999L);
            this.mysqlDao.updateSub(l,"status",true);
            this.mysqlDao.update("update commWxUser set status=0 where openid=?",l.getOperid());
            String confirmUrl = domainName+"/wxPage/WxCancelPlanInit?infoId="+l.getRecid();
            StringBuffer sb=new StringBuffer("因本次申请在24小时内未被审批，系统自动作废申请.");
            sb.append("<a href=").append("'").append(confirmUrl).append("'>详情")
                    .append("</a>");
            UtilTools.sendKfMsg(l.getOperid(),sb.toString());
        });
    }



    public void sendWxInfo() throws WxErrorException {
        long time = new Date().getTime();//当前时间戳
        //log.info("开始检索申请操作信息,时间戳是:"+time);
        //拿到管理者的openid
//        this.mysqlDao.update("UPDATE commAppLog SET STATUS=999 WHERE NOW()>DATE_ADD(`appletime`, INTERVAL 48 HOUR) AND STATUS=2");
        List<CommWxUser> commWxUsers = this.mysqlDao.querySub("select * from commWxUser where usertype=1", CommWxUser.class);
        List<CommAppLog> logs=this.mysqlDao.querySub("select * from commAppLog where status=1",CommAppLog.class);
        logs.forEach(log->{
            commWxUsers.forEach(u->this.SendTemplateInfo(log,u));
            log.setStatus(2L);
            mysqlDao.updateSub(log,"status",true);
        });
//        List<CoPlanCanelinfo> coPlanCanelinfos = this.mysqlDao.querySub("select * from CO_PLAN_CANELINFO where status<>999 and nowdate between ? and ?", new Object[]{time - 7000L, time}, CoPlanCanelinfo.class);
//        for (CoPlanCanelinfo coPlanCanelinfo : coPlanCanelinfos) {
//            for (CommWxUser commWxUser : commWxUsers) {
//                发送模板信息
//                this.SendTemplateInfo(coPlanCanelinfo,commWxUser);
                //sendMessageByKf 客服发送消息
                /*KfSender sender = new KfSender();
                sender.setTouser("oROCnuNihJnO9bnKOAORDFFriPgQ");
                sender.setMsgtype(WxConsts.MASS_MSG_TEXT);
                sender.setText(new SenderContent.Text("hi"));
                System.out.println(iService.sendMessageByKf(sender));*/
//            }
//        }
        //log.info("消息已经消费,将信息给到了处理人"+new Date().getTime());
    }

    /**
     * 模板消息发送
     * @param coPlanCanelinfo
     */
    private void SendTemplateInfo(CommAppLog coPlanCanelinfo, CommWxUser commWxUser) {
        TemplateSender sender = new TemplateSender();
        sender.setTouser(commWxUser.getOpenid());
        sender.setTemplate_id(template_id);
        CoWxTemplateInfo info = new CoWxTemplateInfo();
        info.setFirst(new KeyWord(coPlanCanelinfo.getOpername()+"发起一个方案作废请求需要审批。"));
        info.setKeyword1(new KeyWord("微信申报"));

        Map<String,String> plans=new Gson().fromJson(coPlanCanelinfo.getPlaninf(),Map.class);

        info.setKeyword2(new KeyWord(coPlanCanelinfo.getReason()));
        info.setKeyword3(new KeyWord(coPlanCanelinfo.getOpername()));
        info.setKeyword4(new KeyWord(""));
        info.setKeyword5(new KeyWord(format.format(new Date())));
        String confirmUrl = domainName+"/wxPage/WxCancelPlanInit?infoId="+coPlanCanelinfo.getRecid();
        sender.setUrl(confirmUrl);
        StringBuffer sb=new StringBuffer();
        sb.append("本次申请作废方案如下:\n");
        plans.forEach((k,v)->{
            sb.append(k).append(",").append(v).append("\n");
        });
        info.setRemark(new KeyWord(sb.toString()));
        sender.setData(UtilTools.object2Map(info));
        try {
            TemplateSenderResult result = wxService.templateSend(sender);
            System.out.println(result.toString());
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
}
